#include "widget.h"
#include "ui_widget.h"

const QString SERVER_IP = "127.0.0.1";
const quint16 SERVER_PORT = 8888;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{

    ui->setupUi(this);
    // 区分服务器和客户端
    this->setWindowTitle("客户端");
    client = new QUdpSocket(this);
    // 关联槽函数
    connect(client,&QUdpSocket::readyRead,this,&Widget::processResponse);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::processResponse()
{
    // 1. 获取服务端发送回来的响应
    const QNetworkDatagram& responseDatagram = client->receiveDatagram();
    QString response = responseDatagram.data();
    // 2. 显示到ListWidget
    ui->listWidget->addItem("服务器说：" + response);

}

void Widget::on_pushButton_clicked()
{
    // 1. 获取编辑框中的内容
    const QString& request = ui->lineEdit->text();
    // 2. 构建报文
    //  QHostAddress(const QString &address);
    QNetworkDatagram requestDatagram(request.toUtf8(),QHostAddress(SERVER_IP),SERVER_PORT);
    // 3. 发送数据
    client->writeDatagram(requestDatagram);
    // 4. 将发送数据显示到ListWidget中
    ui->listWidget->addItem("客户端说：" + request);
    // 5. 清空编辑框
    ui->lineEdit->setText("");

}
